<template>
  <div class="container">
    <div class="tab-wrap">
      <div
        v-for="(item, index) in tab"
        :key="index"
        class="tab-item"
        @click="toMain(item)"
      >
        <div v-if="item.midButton" class="mid-button">
          <img :src="item.iconPath" alt="" />
        </div>
        <template v-else>
          <img v-if="current === item.value" :src="item.actIconPath" alt="" />
          <img v-else :src="item.iconPath" alt="" />
          <div :class="{ active: current === item.value }">{{ item.text }}</div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import wx from 'weixin-js-sdk'
import axios from 'axios'
export default {
  name: 'tabBar',
  props: {
    current: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      tab: []
    }
  },
  created() {
    this.getAuthority()
  },
  methods: {
    // 获取用户角色，判断权限
    getAuthority() {
      const roleName = this.$store.getters.roleName
      // console.log('角色：', roleName)
      if (roleName === '检测员') {
        this.tab = [
          {
            value: 0,
            text: '首页',
            iconPath: require('@/assets/img/icon/tab_home_n.png'),
            actIconPath: require('@/assets/img/icon/tab_home_s.png'),
            url: '/'
          },
          {
            value: 2,
            text: '我的',
            iconPath: require('@/assets/img/icon/tab_me_n.png'),
            actIconPath: require('@/assets/img/icon/tab_me_s.png'),
            url: '/me'
          }
        ]
      } else {
        this.tab = [
          {
            value: 0,
            text: '首页',
            iconPath: require('@/assets/img/icon/tab_home_n.png'),
            actIconPath: require('@/assets/img/icon/tab_home_s.png'),
            url: '/'
          },
          {
            value: 1,
            iconPath: require('@/assets/img/icon/tab_scan.png'),
            url: '/scan',
            midButton: true
          },
          {
            value: 2,
            text: '我的',
            iconPath: require('@/assets/img/icon/tab_me_n.png'),
            actIconPath: require('@/assets/img/icon/tab_me_s.png'),
            url: '/me'
          }
        ]
      }
      // if (roleName === '采样员') {
      // } else if (roleName === '检测员') {
      // } else if (roleName === '采样员和检测员') {
      // } else if (roleName === '管理员') {
      // } else {
      // }
    },
    toMain(item) {
      if (item.url === '/scan') {
        this.weChatScan()
      } else {
        this.$router.push(item.url)
      }
    },

    weChatScan() {
      let that = this

      const signUrl = this.$store.getters.signUrl
      const appId = this.$store.getters.appId
      const scanMark = this.$store.getters.scanMark
      // console.log('scanMarket是:', scanMark)

      let formData = new FormData()
      formData.append('appId', appId)
      formData.append('url', window.location.href.split('#')[0])
      axios.post(signUrl, formData).then((res) => {
        if (res.data.code === '0') {
          const newData = res.data.data
          if (newData) {
            wx.config({
              debug: false,
              appId: newData.appId,
              timestamp: newData.timestamp,
              nonceStr: newData.nonceStr,
              signature: newData.signature,
              jsApiList: ['scanQRCode']
            })
            wx.ready(function () {
              console.log('wx ready')
              wx.scanQRCode({
                needResult: 1,
                scanType: ['qrCode'],
                success: function (res) {
                  console.log('wx 扫码 success res:', res)

                  // todo:
                  // 获取前缀
                  // 正式:
                  let url = res.resultStr
                  console.log('scanMark**:', scanMark)
                  console.log('url**:', url)
                  console.log('结果** :', url.indexOf(scanMark))
                  if (url.indexOf(scanMark) === -1) {
                    // 不一致就返回 -1
                    that.$toast.fail('二维码不正确')
                    console.log('二维码不正确')
                    return false
                  }

                  const params = new URLSearchParams(res.resultStr) // 使用URLSearchParams对象解析URL中的查询字符串
                  const code = params.get('code')
                  console.log(
                    'resultStr:',
                    res.resultStr,
                    'params:',
                    params,
                    'code:',
                    code
                  )
                  if (code) {
                    that.$router.push('/scan-details?id=' + code)
                  }
                },
                fail(err) {
                  console.log('wx 扫码 fail err:', err)
                  that.$toast.fail('扫码失败')
                }
              })
            })

            wx.error(function (res) {
              // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
              console.log('wx.error:', res)
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.tab-wrap {
  background-color: #fff;
  height: 60px;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  font-size: 15px;

  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;

    .mid-button {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background-color: #e2ecff;
      border: 4px solid white;
      flex-shrink: 0;
      position: relative;
      bottom: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    div {
      margin-top: 5px;
    }

    .active {
      color: #4e75d0;
    }
  }
}
</style>
